package com.java.controller;

import com.java.config.result.Result;
import com.java.common.utils.RandomUtil;
import com.java.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//短信
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){
        Map<String, Object> map = new HashMap<>();
        //code 这个是 code是发送验证码流程中保存到redis中
        //假数据 手机号 ： code
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok(code);
        }
        //如果为空发送验证码
        //生成6位数验证码
        code = RandomUtil.getSixBitRandom();
        //发送验证码服务 提供假数据
        Boolean send = msmService.send(phone, code);
        //发送是否成功
        //Boolean send = true;
        if(true){
            //设置超时时间为2分钟
            map.put("code",code);
            redisTemplate.opsForValue().set(phone,code,1000, TimeUnit.MINUTES);
            return Result.ok(map);
        }else{
            return Result.fail("发送失败");
        }
    }
}
